<template>
  <div class="container">
    <div class="app-container">
      <el-tree
        :data="treedata"
        :props="defaultProps"
        :default-expand-all="true"
        :expand-on-click-node="false"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span>
            <span class="manager">管理猿</span>

            <el-dropdown @command="handleCommand($event, data.id)">
              <span class="el-dropdown-link">
                操作<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                <el-dropdown-item command="delete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </span>
        </span>
      </el-tree>
    </div>
    <AddDepatVue :pid="pid" :showDialog.sync="showDialog"></AddDepatVue>
  </div>
</template>
<script>
import { getDepartments } from "@/api/department";
import { translateTotree } from "@/utils/index";
import AddDepatVue from "./AddDepat.vue";
export default {
  name: "Department",
  data() {
    return {
      treedata: [], //树形组件的默认
      defaultProps: {
        children: "children",
        label: "name",
      },
      showDialog: false,
      pid: 0,
    };
  },
  components: {
    AddDepatVue,
  },
  created() {
    //获取部门
    this.getDepartmentList();
  },
  methods: {
    async getDepartmentList() {
      const res = await getDepartments();
      this.treedata = translateTotree(res, 0);
    },
    translateTotree(list = [], pid = 0) {
      let result = [];
      list.forEach((item) => {
        if (item.pid === pid) {
          item.children = translateTotree(list, item.id);
          result.push(item);
        }
      });
      return result;
    },
    handleCommand(command, id) {
      this.pid = id;
      if (command === "add") {
        this.showDialog = true;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px 140px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.manager {
  margin-right: 20px;
}
</style>
